package com.issac.vhr.service;

import com.issac.vhr.entity.Hr;
import com.issac.vhr.mapper.HrMapper;
import com.issac.vhr.mapper.Hr_roleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.HrUtils;

import java.util.List;

@Service
public class HrService implements UserDetailsService {
    @Autowired
    HrMapper hrMapper;
    @Autowired
    Hr_roleMapper hr_roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Hr hr = hrMapper.loadUserByUsername(username);
        if (hr == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        hr.setRoles(hrMapper.getHrRolesById(hr.getId()));
        return hr;
    }

    public List<Hr> getAllHrs(String keywords) {
        //展示除自己以外的管理员
        return hrMapper.getAllHrs(HrUtils.getCurrentHr().getId(), keywords);
    }

    public Integer updateHr(Hr hr) {
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    /*
     *   删除hrid下的角色
     *   添加数组角色
     * */
    @Transactional
    public boolean updateHrRole(Integer hrid, Integer[] rids) {
        hr_roleMapper.deleteHrRolesByHrid(hrid);
        return hr_roleMapper.insertHrRoles(hrid, rids) == rids.length;
    }

    /*
     * 应做逻辑删除 这里直接删了
     * */
    public Integer deleteHr(Integer id) {
        return hrMapper.deleteByPrimaryKey(id);
    }

    /*
     *
     *  文件删除
     *
     * */
    public Integer updateHrUserface(String userfaceUrl) {
        return 0;
    }

    public Boolean updateHrPassByHrId(String pass, String oldPass, Integer hrid) {
        Hr hr = hrMapper.selectByPrimaryKey(hrid);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(oldPass, hr.getPassword())) {
            String passEncode = encoder.encode(pass);
            if (hrMapper.updateHrPassByHrId(passEncode, hrid) == 1) {
                return true;
            }
        }
        return false;
    }
}
